import { getAreaTreeApi, getCityTreeApi, getProvinceTreeApi } from "@/api/modules/common/address";
import { onMounted, reactive, toRefs, watch } from "vue";
import { OptionVo } from "../interface";

type AddressStateProps = {
  provinces: OptionVo[];
  citys: OptionVo[];
  areas: OptionVo[];
  province_id: string;
  city_id: string;
  area_id: string;
};

export const useAddress = () => {
  const state = reactive<AddressStateProps>({
    provinces: [],
    citys: [],
    areas: [],
    province_id: "",
    city_id: "",
    area_id: ""
  });

  const getProvinceTree = async () => {
    state.provinces = [];
    state.citys = [];
    state.areas = [];
    state.province_id = "";
    state.city_id = "";
    state.area_id = "";
    const { data } = await getProvinceTreeApi();
    if (data) {
      state.provinces = data as unknown as OptionVo[];
    }
  };

  const getCityTree = async () => {
    state.citys = [];
    state.areas = [];
    state.city_id = "";
    state.area_id = "";
    const { data } = await getCityTreeApi({ provinceId: state.province_id! });
    if (data) {
      state.citys = data as unknown as OptionVo[];
    }
  };

  const getAreaTree = async () => {
    state.areas = [];
    state.area_id = "";
    const { data } = await getAreaTreeApi({ cityId: state.city_id! });
    if (data) {
      state.areas = data as unknown as OptionVo[];
    }
  };

  onMounted(() => {
    getProvinceTree();
  });

  watch(
    () => state.province_id,
    () => {
      console.log("provinceId变化了", state.province_id);
      if (state.province_id) {
        getCityTree();
      }
    },
    { immediate: false }
  );

  watch(
    () => state.city_id,
    () => {
      if (state.city_id) {
        getAreaTree();
      }
    },
    { immediate: false }
  );

  return {
    ...toRefs(state)
  };
};
